package top.honlnk.czuan.service.impl.module.get;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.honlnk.czuan.mapper.get.GetPartSpeechMapper;
import top.honlnk.czuan.pojo.entity.PartSpeech;

@Slf4j
@Component
public class GetPartSpeechSIModule {
    @Autowired
    private GetPartSpeechMapper getPartSpeechMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String PART_SPEECH_SIMPLE_TO_ID = "partSpeechSimpleToId";
    private static final String PART_SPEECH_ID_TO_SIMPLE = "partSpeechIdToSimple";

    public Integer getPartIdBySimple(String partSimple) {
        // 添加redis 缓存
        // 1. 尝试从Redis获取值
        if (redisTemplate.opsForHash().hasKey(PART_SPEECH_SIMPLE_TO_ID, partSimple)) {
            return (Integer) redisTemplate.opsForHash().get(PART_SPEECH_SIMPLE_TO_ID, partSimple);
        }
        // 2. 如果不存在，则从数据库获取值
        PartSpeech partSpeech = getPartSpeechMapper.getPartSpeechBySimple(partSimple);
        if (partSpeech == null) {
            return null;
        }
        // 3. 将其存入缓存
        redisTemplate.opsForHash().put(PART_SPEECH_SIMPLE_TO_ID, partSimple, partSpeech.getId());

        return partSpeech.getId();
    }

    public String getPartSimpleById(Integer partId) {
        // 添加redis 缓存
        // 1. 尝试从Redis获取值
        if (redisTemplate.opsForHash().hasKey(PART_SPEECH_SIMPLE_TO_ID, partId)) {
            return (String) redisTemplate.opsForHash().get(PART_SPEECH_SIMPLE_TO_ID, partId);
        }
        // 2. 如果不存在，则从数据库获取值
        PartSpeech partSpeech = getPartSpeechMapper.getPartSpeechById(partId);
        if (partSpeech == null) {
            return null;
        }

        // 3. 将其存入缓存
        redisTemplate.opsForHash().put(PART_SPEECH_ID_TO_SIMPLE, partId, partSpeech.getSimple());

        return partSpeech.getSimple();
    }
}
